package com.example.wc.logindemo;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.wc.logindemo.getdownload.Image;
import com.example.wc.logindemo.getdownload.ImageLab;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static android.R.color.black;
import static com.example.wc.logindemo.LoginDemoActivity.ACCESS;

/**
 * Created by hui on 2017/1/13.
 */

public class VolleyRequestDemo {

    private final String URL_LOGIN = "http://192.168.2.116/user/api/login";
    private final String URL_BLOGS = "http://192.168.2.116/diyerland/api/blogs?blog=0&size=100";
    private final String URL_ADD = "http://192.168.2.116/diyerland/api/blogadd";
    private final String URL_REMOVE = "http://192.168.2.116/diyerland/api/blogremove";
    private final String URL_EDIT = "http://192.168.2.116/diyerland/api/blogById?blogId=";
    private final String URL_IMAGE = "http://192.168.2.116/user/api/images";
    private JsonObjectRequest jsonObjectRequest;
    private JSONObject mResponse;

    private BlogLab.Content responseSave;
    private Blog mBlog;
    private ImageLab.Images mImages;

    private Integer error;

//    private RequestQueue mQueue;

//    public VolleyRequestDemo(Context context){
//        mQueue = Volley.newRequestQueue(context);
//    }

    public JSONObject getResponse() {
        return mResponse;
    }

    public BlogLab.Content getResponseSave() {
        return responseSave;
    }



    public JsonObjectRequest getJsonObjectRequest() {
        return jsonObjectRequest;
    }

    //    public RequestQueue VolleyRequestQueue(Context context){
//        RequestQueue queue = Volley.newRequestQueue(context);
//        return queue;
//    }

    public void volleyRequestDemo_POST_Login(final Context context, final BlogPostListener loginListener){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile","15736723671");
            jsonObject.put("password","e10adc3949ba59abbe56e057f20f883e");
//                    params.put("mobile",mUser.getText().toString());
//                    params.put("password",mUsers.getPassword());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        volleyRequestDemo_POST(URL_LOGIN, context, jsonObject, loginListener);
    }

    public interface BlogGetListener{
        public void onBlogGeted(BlogLab.Content content);
    }
    public void volleyRequestDemo_GET(final Context context, final BlogGetListener listener) {

        //此处是主线程，main
        jsonObjectRequest = new JsonObjectRequest(
                URL_BLOGS,
                null,
                //所以子线程可以访问到JsonObject的这个成员变量，在网络成功的时候，由子线程调用
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //这里是子线程
                        Gson gson = new Gson();
                        responseSave = gson.fromJson(response.toString(), BlogLab.Content.class);
                        Log.d("TAG", responseSave.toString());
                        //发回通知，数据已经取到
                        if(listener != null){
                            listener.onBlogGeted(responseSave);
                        }
                        //子线程到此结束，运行完成退出
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context,error.getMessage(),Toast.LENGTH_SHORT).show();
                    }
        });
        //这里创建一个子线程，发起网络请求，但是参数是跨线程传递的
        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }

    public void volleyRequestDemo_POST(String url, final Context context, JSONObject jsonObject,
                                       final BlogPostListener listener){
        jsonObjectRequest = new JsonObjectRequest(
                url,
                jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        if(response == null)
                            return;

                        try {
                            error = (Integer) response.get("error");
                            if(error == 0) {
                                mResponse = response;
                                Log.d("TAG", "成功");
                              if(listener != null){
                                listener.onBlogPosted();
                            }
                            }

                        } catch (JSONException e) {
//                                    e.printStackTrace();
//                            Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
                            Toast.makeText(context,"错误代码:" + error,Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                        Toast.makeText(context,error.getMessage(),Toast.LENGTH_SHORT).show();
                        Toast.makeText(context,"网络错误！",Toast.LENGTH_SHORT).show();
                    }
                }
        ){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                headers.put("accessToken", ACCESS);
                return headers;
            }
        };

        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }


    public interface BlogPostListener{
        public void onBlogPosted();
    }

    //添加博客文章
    public void volleyRequestDemo_POST_Add(final Context context, String name, String content,
                                           final BlogPostListener blogAddListener){
        JSONObject jsonObject = new JSONObject();

        try {
//                    jsonObject.put("name", "江城子");
//                    jsonObject.put("content", "十年生死两茫茫，不思量，自难忘。");
            jsonObject.put("name", name);
            jsonObject.put("content", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        volleyRequestDemo_POST(URL_ADD, context, jsonObject, blogAddListener);
    }

    //删除博客文章
    public void volleyRequestDemo_POST_Remove(Context context, String id,
                                              final BlogPostListener blogRemoveListener){

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        volleyRequestDemo_POST(URL_REMOVE, context, jsonObject, blogRemoveListener);
    }

    //编辑博客文章
    public void volleyRequestDemo_POST_Edit(Context context, String id, String name,
                                            String content, final BlogPostListener blogEditListener){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("id", id);
            jsonObject.put("name", name);
            jsonObject.put("content", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        volleyRequestDemo_POST(URL_ADD, context, jsonObject, blogEditListener);
    }

    //获取ID对应的blog读取出来的监听器
    public interface BlogGetBlogListener{
        public void onBlogGetBloged(Blog blog);
    }

    //获取ID对应的blog
    public void volleyRequestDemo_GET_Blog(Context context, String id, final BlogGetBlogListener listener){
        String url_id = URL_EDIT + id;
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url_id,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Gson gson = new Gson();
                        mBlog = gson.fromJson(response.toString(), Blog.class);

                        if(listener != null){
                            listener.onBlogGetBloged(mBlog);
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("error", error.toString());

                    }
                }
        ){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError{
                HashMap<String, String> headers = new HashMap<String, String>();
//                headers.put("Content-Type", "application/json");
                headers.put("accessToken", ACCESS);
                return headers;
            }
        };
        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }

    public interface ImageGetListener{
        public void onImageGeted(ImageLab.Images images);
    }

    public void volleyRequestDemo_GET_Image(final Context context, final ImageGetListener listener) {

        //此处是主线程，main
        jsonObjectRequest = new JsonObjectRequest(
                URL_IMAGE,
                null,
                //所以子线程可以访问到JsonObject的这个成员变量，在网络成功的时候，由子线程调用
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //这里是子线程
                        Gson gson = new Gson();
                        mImages = gson.fromJson(response.toString(), ImageLab.Images.class);
                        Log.d("TAG", mImages.toString());
                        //发回通知，数据已经取到
                        if(listener != null){
                            listener.onImageGeted(mImages);
                        }
                        //子线程到此结束，运行完成退出
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context,error.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError{
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("token", ACCESS);
                        return headers;
                    }
                };
        //这里创建一个子线程，发起网络请求，但是参数是跨线程传递的
        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }

}
